<template>
  <div class="app-container">
    <!-- Tab 切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane label="正在养殖" name="0" />
      <el-tab-pane label="养殖完成" name="1" />
    </el-tabs>

    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="养殖池编号" prop="tankCode">
        <el-select
          v-model="queryParams.tankCode"
          placeholder="请选择养殖池编号"
          clearable
          filterable
          style="width: 180px"
        >
          <el-option
            v-for="item in currentTankCodeOptions"
            :key="item.tankCode"
            :label="item.tankCode"
            :value="item.tankCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属区域" prop="areaId">
        <el-select v-model="queryParams.areaId" placeholder="请选择所属区域" clearable style="width: 180px">
          <el-option v-for="item in areaOptions" :key="item.id" :label="item.areaName" :value="item.id" />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="创建者" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建者" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <!-- 工具栏：只在“正在养殖”显示 -->
    <el-row :gutter="10" class="mb8" v-if="isBreedingTab">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['SysTanks:SysTanks:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['SysTanks:SysTanks:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['SysTanks:SysTanks:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="refreshActive" />
    </el-row>

    <!-- 表格 -->
    <el-table
        v-loading="loading"
        :data="isBreedingTab ? breedingList : finishedList"
        @selection-change="handleSelectionChange"
      >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="养殖池编号" align="center" prop="tankCode" />
      <el-table-column label="池高" align="center" prop="heightCm" />
      <el-table-column label="养殖池的水体量" align="center" prop="capacityL" />
      <el-table-column label="养殖生物" align="center" prop="speciesId">
        <template #default="scope">
          <span>
            {{ speciesOptions.find(s => s.id === scope.row.speciesId)?.speciesName || scope.row.speciesId }}
          </span>
        </template>
      </el-table-column>
<!--      <el-table-column label="产成重量" align="center" prop="yieldWeight" />-->
<!--      <el-table-column label="海马数量" align="center" prop="seahorseQuantity" />-->
      <el-table-column label="所属区域" align="center" prop="areaName" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="生物图" align="center" prop="imageUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 正在养殖：保留原来功能 + 完成 -->
          <template v-if="isBreedingTab">
            <el-button link type="primary" icon="Edit"   @click="handleUpdate(scope.row)" v-hasPermi="['SysTanks:SysTanks:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" style="margin-left: 4px" @click="handleDelete(scope.row)" v-hasPermi="['SysTanks:SysTanks:remove']">删除</el-button>
<!--            <el-button link type="primary" icon="Document" @click="goGrowthRecords(scope.row)">生长记录</el-button>-->
<!--            <el-button link type="primary" icon="Document" @click="goFeedingRecords(scope.row)">投喂记录</el-button>-->
<!--            <el-button link type="primary" icon="Plus" @click="markAsFinished(scope.row)">完成</el-button>-->
            <el-dropdown trigger="click">
              <el-button link type="primary" icon="DArrowRight" style="margin-top: 2px;margin-left: 5px">更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Document" @click="goGrowthRecords(scope.row)">生长记录</el-dropdown-item>
                  <el-dropdown-item icon="Document" @click="goFeedingRecords(scope.row)">投喂记录</el-dropdown-item>
                  <el-dropdown-item icon="Plus" @click="markAsFinished(scope.row)">完成</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>

          <!-- 养殖完成：去掉新增/修改/删除，仅保留“取消 + 记录查看” -->
          <template v-else>
            <el-button link type="primary" icon="RefreshLeft" @click="undoFinished(scope.row)">取消</el-button>
            <el-button link type="primary" icon="Delete" style="margin-left: 4px" @click="handleDelete(scope.row)">删除</el-button>
<!--            <el-button link type="primary"  icon="Document"   @click="goGrowthRecords(scope.row)">生长记录</el-button>-->
<!--            <el-button link type="primary"  icon="Document"   @click="goFeedingRecords(scope.row)">投喂记录</el-button>-->
            <el-dropdown trigger="click">
              <el-button link type="primary" icon="DArrowRight" style="margin-top: 2px">更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Document"   @click="goGrowthRecords(scope.row)">生长记录</el-dropdown-item>
                  <el-dropdown-item icon="Document"   @click="goFeedingRecords(scope.row)">投喂记录</el-dropdown-item>
<!--                  <el-dropdown-item type="warning" icon="RefreshLeft"   @click="undoFinished(scope.row)">取消</el-dropdown-item>-->
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页：跟随当前 Tab 的 total -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="fetchCurrent"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="SysTanksRef" :model="form" :rules="rules" label-width="100px" style="margin-left: 5px">
        <el-row>
          <el-col :span="12">
        <el-form-item label="养殖池编号" prop="tankCode">
          <el-input v-model="form.tankCode" placeholder="请输入养殖池编号" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="模板选择" prop="modelId">
          <el-select
            v-model="form.modelId"
            placeholder="请选择模板"
            clearable
            filterable
            @change="handleTemplateChange"
            style="width: 100%"
          >
            <el-option
              v-for="item in modelOptions"
              :key="item.modelId"
              :label="`模板-${item.modelId}（高:${item.heightCm}cm, 容积:${item.capacityL}L）`"
              :value="item.modelId"
            />
          </el-select>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属区域" prop="areaId">
              <el-select v-model="form.areaId" placeholder="请选择所属区域">
                <el-option v-for="item in areaOptions" :key="item.id" :label="item.areaName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择养殖池状态" clearable>
            <el-option
                v-for="s in statusOptions"
                :key="s.value"
                :label="s.label"
                :value="s.value"
            />
          </el-select>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="养殖生物" prop="speciesId">
              <el-select v-model="form.speciesId" placeholder="请选择养殖生物">
                <el-option v-for="item in speciesOptions" :key="item.id" :label="item.speciesName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
            <el-col :span="12">
              <el-form-item label="池高" prop="heightCm">
                <el-input v-model="form.heightCm" placeholder="请输入池高(cm)" />
              </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="产成重量" prop="yieldWeight">
              <el-input v-model="form.yieldWeight" placeholder="请输入产成重量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="海马数量" prop="seahorseQuantity">
              <el-input v-model="form.seahorseQuantity" placeholder="请输入海马数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="养殖池水体量" prop="capacityL">
          <el-input v-model="form.capacityL" placeholder="请输入桶容积(L)" />
        </el-form-item>
        <el-form-item label="生物图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysTanks">
import { ref, reactive, toRefs, computed, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { listSysTanks, getSysTanks, delSysTanks, addSysTanks, updateSysTanks } from '@/api/SysTanks/SysTanks'
import { listSysAquaticSpecies } from '@/api/SysAquaticSpecies/SysAquaticSpecies'
import { listSysTanksArea } from '@/api/SysTanksArea/SysTanksArea'
import { listSysModelTanks } from '@/api/SysModel/SysModelTanks'
const router = useRouter()
const { proxy } = getCurrentInstance()
/** 下拉项 */
const speciesOptions = ref([])
const areaOptions = ref([])
const tankCodeOptions = ref([])
const modelOptions = ref([]) // 存储养殖桶模板选项
const statusOptions = ref([
  { label: '正常', value: '正常' },
  { label: '空池', value: '空池' },
  { label: '异常', value: '异常' },
  { label: '预警', value: '预警' },
  //{ label: '繁殖', value: '繁殖' },
  // 如果以后还有其他状态，直接在这里补就行
])
/** UI 状态 */
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const title = ref('')
const total = ref(0)
/** Tab & 列表 & 分页 */
const activeTab = ref('0') // '1' 正在养殖 | '0' 养殖完成
const isBreedingTab = computed(() => String(activeTab.value) === '0')

const breedingList  = ref([]) // isFinished = 1
const finishedList  = ref([]) // isFinished = 0
const totalBreeding = ref(0)
const totalFinished = ref(0)

/** 查询/表单 */
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tankCode: null,
    areaId: null,
    status: null,
    createBy: null,
    remark: null,
    speciesId: null,
    heightCm: null,
    capacityL: null,
    imageUrl: null,
  },
  rules: {
    tankCode: [
      { required: true, message: "桶编号不能为空", trigger: "blur" }
    ],
    heightCm: [
      { required: false, message: "桶高", trigger: "blur" },
      { pattern: /^\d+(\.\d{1,2})?$/, message: "桶高必须为数字，最多保留两位小数", trigger: "blur" }
    ],
    capacityL: [
      { required: false, message: "养殖池的水体量", trigger: "blur" },
      { pattern: /^\d+(\.\d{1,2})?$/, message: "养殖池的水体量必须为数字，最多保留两位小数", trigger: "blur" }
    ],
    areaId: [
      { required: true, message: "所属区域不能为空", trigger: "change" }
    ],
    // speciesId: [
    //   { required: true, message: "养殖生物不能为空", trigger: "change" }
    // ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    // imageUrl: [
    //   { required: true, message: "请上传养殖生物图", trigger: "change" }
    // ]
    yieldWeight: [
      { pattern: /^\d+(\.\d+)?$/, message: "产成重量请输入数字", trigger: "blur" }
    ],
    seahorseQuantity: [
      { pattern: /^\d+(\.\d+)?$/, message: "海马数量请输入数字", trigger: "blur" }
    ]
  }
})
const { queryParams, form, rules } = toRefs(data)
// 获取所有桶编号作为下拉框选项
function getTankCodeOptions() {
  listSysTanks({ pageNum: 1, pageSize: 1000 }).then(res => {
    tankCodeOptions.value = res.rows || []
  })
}
// 在 script setup 中添加计算属性
const currentTankCodeOptions = computed(() => {
  if (isBreedingTab.value) {
    // 正在养殖：只显示 isFinished=1 的养殖池
    return tankCodeOptions.value.filter(item => item.isFinished === '1')
  } else {
    // 养殖完成：只显示 isFinished=0 的养殖池
    return tankCodeOptions.value.filter(item => item.isFinished === '0')
  }
})
/* ----------- 数据获取（分别获取两类） ----------- */
function fetchBreeding() {
  loading.value = true
  const p = { ...queryParams.value, isFinished: '1' }
  return listSysTanks(p).then(res => {
    breedingList.value  = res?.rows || []
    totalBreeding.value = res?.total || 0
  }).finally(() => {
    loading.value = false
  })
}
// 刷新当前 Tab（带分页）
function fetchCurrent() {
  loading.value = true
  const isFinished = isBreedingTab.value ? '1' : '0' // 永远用字符串
  const params = { ...queryParams.value, isFinished }
  return listSysTanks(params)
    .then(res => {
      if (isBreedingTab.value) {
        breedingList.value = res?.rows || []
      } else {
        finishedList.value = res?.rows || []
      }
      total.value = res?.total || 0
    })
    .finally(() => (loading.value = false))
}

function fetchFinished() {
  loading.value = true
  const p = { ...queryParams.value, isFinished: '0' }
  return listSysTanks(p).then(res => {
    finishedList.value  = res?.rows || []
    totalFinished.value = res?.total || 0
  }).finally(() => {
    loading.value = false
  })
}

/** 同时加载两类（首次/搜索/重置用） */
function fetchBoth() {
  loading.value = true
  const base = { ...queryParams.value }
  return Promise.all([
    listSysTanks({ ...base, isFinished: '1' }),
    listSysTanks({ ...base, isFinished: '0' })
  ]).then(([res0, res1]) => {
    breedingList.value  = res0?.rows || []
    totalBreeding.value = res0?.total || 0
    finishedList.value  = res1?.rows || []
    totalFinished.value = res1?.total || 0
  }).finally(() => {
    loading.value = false
  })
}

function undoFinished(row) {
  updateSysTanks({ id: row.id, isFinished: '1' }).then(() => {
    proxy.$modal.msgSuccess('已取消完成，已移回“正在养殖”')
    finishedList.value = finishedList.value.filter(it => it.id !== row.id)
    breedingList.value = [{ ...row, isFinished: 1 }, ...breedingList.value]
    if (!isBreedingTab.value) total.value = Math.max(0, total.value - 1)
  })
}

function handleTabChange(tab) {
  activeTab.value = String(tab?.props?.name ?? '0')
  queryParams.value.pageNum = 1
  fetchCurrent()
}

/** 初始化：默认加载正在养殖 */
onMounted(() => {
  activeTab.value = '0'
  fetchCurrent()
  getSpeciesOptions()
  getAreaOptions()
  getTankCodeOptions()
  getModelOptions()
  console.log('表格数据', isBreedingTab)
  console.log('表格数据', breedingList)
  console.log('表格数据', finishedList)
})

/** 搜索按钮 */
function handleQuery() {
  queryParams.value.pageNum = 1
  fetchCurrent()
}

/** 重置按钮 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 分页变化（只刷当前 tab） */
function handlePageChange() {
  isBreedingTab.value ? fetchBreeding() : fetchFinished()
}

/** 多选框 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 只刷新当前 tab（工具栏右上角重载） */
function refreshActive() {
  isBreedingTab.value ? fetchBreeding() : fetchFinished()
}

/** 标记为完成（只动这一行，本地移动，不跳 Tab、不整页刷新） */
function markAsFinished(row) {
  const payload = { id: row.id, isFinished: '0' } // 只提交必要字段，并用字符串'1'
  updateSysTanks(payload).then(() => {
    proxy.$modal.msgSuccess('已标记为养殖完成')
    // 本地移动：从正在养殖移除，推入养殖完成
    breedingList.value = breedingList.value.filter(it => it.id !== row.id)
    finishedList.value = [{ ...row, isFinished: 1 }, ...finishedList.value]
    // 当前tab总数-1（在正在养殖Tab下）
    if (isBreedingTab.value) total.value = Math.max(0, total.value - 1)
  })
}

/* ----------- 其它按钮（新增/改/删）保持原来逻辑 ----------- */
function goGrowthRecords(row) {
  router.push({ path: '/SysGrowthRecords', query: { tankCode: row.tankCode } })
}
function goFeedingRecords(row) {
  router.push({ path: '/SysFeedingRecords', query: { tankCode: row.tankCode } })
}

function getSpeciesOptions() {
  listSysAquaticSpecies({ pageNum: 1, pageSize: 1000, status: 1 }).then(res => {
    speciesOptions.value = res.rows || []
  })
}
// function getAreaOptions() {
//   listSysTanksArea({ pageNum: 1, pageSize: 1000 }).then(res => {
//     areaOptions.value = res.rows || []
//   })
//}

function getAreaOptions() {
  // ① 首选：服务端过滤（若后端支持 status 查询）
  listSysTanksArea({ pageNum: 1, pageSize: 1000, status: 1 }).then(res => {
    // ② 兜底：前端再过滤一遍，兼容后端返回字符串/数字
    const rows = res?.rows ?? []
    areaOptions.value = rows.filter(item => Number(item?.status) === 1)
  })
}

// 获取养殖桶模板列表（用于模板选择）
function getModelOptions() {
  listSysModelTanks({ pageNum: 1, pageSize: 999 })
    .then(res => {
      modelOptions.value = res.rows || []
    })
    .catch(err => {
      console.error('获取养殖桶模板失败:', err)
      proxy.$modal.msgError('获取模板数据失败')
    })
}

/** 选择模板后自动填充池高和养殖池的水体量 */
function handleTemplateChange(modelId) {
  if (!modelId) return // 清空选择时不处理

  const selected = modelOptions.value.find(m => m.modelId === modelId)
  if (selected) {
    // 自动填充但不覆盖用户可能已输入的内容（除非你希望强制覆盖）
    if (!form.value.heightCm) {
      form.value.heightCm = selected.heightCm
    }
    if (!form.value.capacityL) {
      form.value.capacityL = selected.capacityL
    }

    // 可选：强制覆盖（更符合“选择模板”的语义）
    form.value.heightCm = selected.heightCm
    form.value.capacityL = selected.capacityL
  }
}

/** 弹窗：取消 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    tankCode: null,
    areaName: null,
    status: '空池',
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    speciesId: null,
    areaId: null,
    heightCm: null,
    capacityL: null,
    isFinished: 1,
    imageUrl: null,
    modelId: null,
    yieldWeight: null,
    seahorseQuantity: null,
  }
  proxy.resetForm('SysTanksRef')
}

/** 新增 */
function handleAdd() {
  reset()
  getSpeciesOptions()
  getAreaOptions()
  open.value = true
  title.value = '添加养殖池'
}

/** 修改（支持工具栏和行内两种入口） */
function handleUpdate(row) {
  reset()
  getSpeciesOptions()
  getAreaOptions()
  const _id = row?.id || ids.value[0]
  if (!_id) {
    proxy.$modal.msgWarning('请先选择一条数据')
    return
  }
  getSysTanks(_id).then(res => {
    form.value = res.data
    open.value = true
    title.value = '修改养殖池'
  })
}

/** 提交（新增/修改） */
function submitForm() {
  proxy.$refs['SysTanksRef'].validate(valid => {
    if (!valid) return

    // 打印调试
    console.log("提交表单数据：", form.value)

    // 如果用户没选，就交给后端默认值；如果用户选了，必须带过去
    const payload = { ...form.value }
    if (form.value.status) {
      payload.status = form.value.status
    }

    const api = form.value.id != null ? updateSysTanks : addSysTanks
    api(payload).then(() => {
      proxy.$modal.msgSuccess(form.value.id != null ? '修改成功' : '新增成功')
      open.value = false
      fetchCurrent()
    })
  })
}

/** 删除（工具栏/行内） */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除养殖池编号为"' + _ids + '"的数据项？')
    .then(() => delSysTanks(_ids))
    .then(() => {
      proxy.$modal.msgSuccess('删除成功')
      fetchCurrent()
    })
    .catch(() => {})
}
</script>